package jgl.vajra.kingkong.widget.manager;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import androidx.annotation.RequiresApi;


/**
 * Created by Administrator on 2019/6/24.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class JobServiceSchedulerManager {
    public final static int JOBID_TOKEN_ID = 10086;
    public final static int JOBID_MESSAGE_COUNT_ID = 10087;
    public static int JOBID_TOKEN_REQUESTINTERVAL = 60 * 60 * 1000;
    public static int JOBID_MESSAGE_COUNT_REQUESTINTERVAL = 3 * 60 * 1000;


    private static class JobServiceSchedulerManagerSingleton {
        private static final JobServiceSchedulerManager INSTANCE = new JobServiceSchedulerManager();

    }

    public static JobServiceSchedulerManager getInstance() {
        return JobServiceSchedulerManager.JobServiceSchedulerManagerSingleton.INSTANCE;
    }

    private JobServiceSchedulerManager() {

    }





    //将任务作业发送到作业调度中去
    public void scheduleJob(Context context, JobInfo t, int jobId, boolean isCheckCancel) {
        JobScheduler tm = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            tm = context.getSystemService(JobScheduler.class);
        } else {
            tm = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
        }
        if (tm != null) {
            tm.cancel(jobId);
            tm.schedule(t);
        }
    }

    public JobInfo getJobInfo(Context context, int jobId, Class<?> clazz, long requestInterval) {

        //代表一个任务 使用建造者模式建造
        JobInfo jobInfo;
        // Android7上,设置周期执行时间，会强制按照getMinPeriodMills阈值执行，此时设置任务执行最小时间间隔解决该问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            jobInfo = new JobInfo.Builder(jobId, new ComponentName(context, clazz))
                    .setBackoffCriteria(requestInterval, JobInfo.BACKOFF_POLICY_LINEAR)
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
                    .setMinimumLatency(requestInterval)
                    .setOverrideDeadline(requestInterval)
                    .setPersisted(true)
                    .build();
        } else {
            jobInfo = new JobInfo.Builder(jobId, new ComponentName(context, clazz))
                    .setBackoffCriteria(requestInterval, JobInfo.BACKOFF_POLICY_LINEAR)//设置线性重试策略
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) //设置网络类型
                    .setPeriodic(requestInterval) //设置执行周期
                    .setPersisted(true)//设置重启后任务是否保留
                    .build();
        }
        return jobInfo;
    }

}
